const express = require('express')
const validate = require('express-validation')
const validation = require('../validation')
const shopController = require('../controller/shopController')
const userController = require('../controller/userController')
const accountController = require('../controller/accountController')
const tokenController = require('../controller/tokenController')
const kindController = require('../controller/kindController')
const goodController = require('../controller/goodController')
const errorHelper = require('../util/errorHelper')
const tokenChecker = require('../util/tokenChecker')
const _ = require('lodash')

const shopRouter = express.Router()
const defaultShopAvatar = 'http://p6suk2a3h.bkt.clouddn.com/defaultAvatar.png'
const defaultShopName = 'Default Name'

/* 注册 */
shopRouter.post('/signup', validate(validation.shopSignup), async (req, res, next) => {
  const { email, password, confirmPass } = req.body
  if (confirmPass !== password) {
    errorHelper(400, 'confirmPass not same with password')
  }
  try {
    const avatar = defaultShopAvatar
    const name = defaultShopName
    const shopId = await accountController.createAccount({
      type: 'shop',
      email,
      password,
      avatar,
      name
    })
    const result = {
      status: 200,
      msg: '注册成功',
      data: {
        shopId
      }
    }
    res.json(result)
  } catch (e) {
    // 如果error没有status字段说明是数据库抛出的错误，同一处理为服务器错误
    next(e)
  }
})
/* 登录 */
shopRouter.post('/login', validate(validation.shopLogin), async (req, res, next) => {
  const { identityType, identifier, password } = req.body
  const device = req.headers['user-agent']
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  try {
    const { accountDetail, token } = await accountController.login({
      type: 'shop',
      identityType,
      identifier,
      password,
      device,
      ip
    })
    res.json({
      status: 200,
      msg: '登录成功',
      data: {
        shopDetail: accountDetail,
        token
      }
    })
  } catch (e) {
    next(e)
  }
})
/* 获取店铺详情 */
shopRouter.get('/:shopId/info', async (req, res, next) => {
  const { shopId } = req.params
  const { headers } = req
  const token = (headers.authorization && headers.authorization.split('token ')[1]) || null
  try {
    // start token检查
    let isTokenValid = false
    if (token) {
      isTokenValid = await tokenController.checkToken(token)
    }
    // end token检查
    const shopDetail = await shopController.getDetailByShopId(shopId, isTokenValid)
    res.json({
      status: 200,
      msg: '获取店铺信息成功',
      data: {
        shop: shopDetail
      }
    })
  } catch (e) {
    next(e)
  }
})
/* 编辑店铺详情 */
shopRouter.post('/editInfo', tokenChecker, async (req, res, next) => {
  const { shopInfo } = req.body
  try {
    const result = await shopController.saveInfo(shopInfo)
    if (result) {
      res.json({
        status: 200,
        msg: '保存成功',
        data: {}
      })
    } else {
      errorHelper(500, 'field error')
    }
  } catch (e) {
    next(e)
  }
})
/* 获取店铺所有商品 */
shopRouter.get('/:shopId/goods', async (req, res, next) => {
  const { shopId } = req.params
  try {
    const goods = await goodController.getGoods({
      shopId,
      page: '',
      countPerPage: ''
    })
    res.json({
      status: 200,
      msg: '获取店铺商品成功',
      data: {
        goods
      }
    })
  } catch (e) {
    next(e)
  }
})
/* 点击增加点击量 */
shopRouter.post('/clickRate', async (req, res, next) => {
  const { shopId } = req.body
  try {
    const result = await shopController.addClickRate(shopId)
    res.json({
      status: 200,
      msg: '点击量增加成功',
      data: {}
    })
  } catch (e) {
    next(e)
  }
})
/* 获取热门店铺 */
shopRouter.get('/hot', async (req, res, next) => {
  try {
    const hotShops = await shopController.getHotShops()
    res.json({
      status: 200,
      msg: '获取热门店铺成功',
      data: {
        hotShops
      }
    })
  } catch (e) {
    next(e)
  }
})

shopRouter.post('/search', async (req, res, next) => {
  try {
    const keyWords = req.body.keyWords.split(' ')
    const shops = await shopController.search(keyWords)
    res.json({
      status: 200,
      msg: '搜索店铺成功',
      data: {
        shops
      }
    })
  } catch (e) {
    next(e)
  }
})

shopRouter.post('/checkToken', tokenChecker, async (req, res, next) => {
  const { type, uuId } = req
  try {
    const result = {}
    if (type === 'shop') {
      result.shop = await shopController.getDetailByShopId(uuId, true)
    } else if (type === 'user') {
      result.user = await userController.getDetailByUserId(uuId, true)
    }
    res.json({
      status: 200,
      msg: 'token 有效',
      data: result
    })
  } catch (e) {
    next(e)
  }
})

module.exports = shopRouter
